package team.star.werespos.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import team.star.werespos.config.shiro.CurrPrincipal;
import team.star.werespos.exception.GlobalException;
import team.star.werespos.model.entity.User;
import team.star.werespos.model.enums.CodeMsgEnum;
import team.star.werespos.model.vo.NewPwdVO;
import team.star.werespos.model.vo.ResultVO;
import team.star.werespos.service.UserService;
import team.star.werespos.util.Result;

import javax.validation.Valid;
import java.util.List;

/**
 * UserController class<br/>
 *
 * @author hdonghong
 * @since 2019/04/08
 */
@Slf4j
@RequestMapping("/admin/user")
@RestController
public class UserController {
    @Autowired
    private UserService userService;

    @PostMapping("/new")
    public ResultVO<?> newUser(@RequestBody User user) {
        userService.insertOne(user);
        return Result.success(user);
    }


    /**
     * 获取用户列表
     * @return
     */
    @GetMapping("/list")
    public ResultVO<List<User>> listUsers(){
        return Result.success(
                userService.listUsers()
        );
    }

    /**
     * 修改当前用户密码
     *
     */
    @PostMapping("/update/pwd")
    public ResultVO<?> updatePwd(
            @RequestBody @Valid NewPwdVO newPwdVO) {

        userService.updatePassword(newPwdVO.getOldPwd(), newPwdVO.getNewPwd());
        return Result.success();
    }

    /**
     * 修改用户信息
     *
     */
    @PostMapping("/{uid}/update")
    public ResultVO<?> updateById(@PathVariable Integer uid,
                                  @RequestBody @Valid User user) {
        user.setUid(uid);
        // 不允许修改用户名
        user.setUsername(null);
        // 不允许修改盐
        user.setSalt(null);
        if (CurrPrincipal.get().getUid().equals(uid)) {
            // 不允许通过此接口修改当前用户密码
            user.setPassword(null);
        }
        userService.updateById(user);
        return Result.success();
    }

    /**
     * 删除用户
     */
    @GetMapping("/{uid}/delete")
    public ResultVO<?> deleteById(@PathVariable Integer uid) {
        if (uid.equals(CurrPrincipal.get().getUid())) {
            log.info("[deleteById] CodeMsgEnum.USER_INVALID_DELETE = {}", CodeMsgEnum.USER_INVALID_DELETE);
            throw GlobalException.create(CodeMsgEnum.USER_INVALID_DELETE);
        }
        userService.deleteById(
                new User().setUid(uid)
        );
        return Result.success();
    }

    /**
     * 获取用户信息
     * */
    @GetMapping({"/{uid}/profile"})
    public ResultVO<?> getProfile(
            @PathVariable(name = "uid") Integer uid) {
        return Result.success(userService.getOne(uid));
    }
}
